package com.xiyu.service.repository.nurse.plan;

import com.xiyu.service.model.nurse.item.NurseItemFetcher;
import com.xiyu.service.model.nurse.plan.NursePlan;
import com.xiyu.service.model.nurse.plan.NursePlanDetailFetcher;
import com.xiyu.service.model.nurse.plan.NursePlanFetcher;
import com.xiyu.service.model.nurse.plan.NursePlanTable;
import com.xiyu.service.vo.nurse.nursePlan.NursePlanPageInput;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;

import java.util.Optional;

public interface NursePlanRepository extends JRepository<NursePlan, Long> {
    NursePlanTable nursePlanTable = NursePlanTable.$;

    Optional<NursePlan> findFirstByPlanName(String planName);

    Optional<NursePlan> findFirstByPlanNameAndIdNot(String planName, Long id);

    default Optional<NursePlan> getById(Long id){
        return sql().createQuery(nursePlanTable)
                .where(nursePlanTable.id().eq(id))
                .select(nursePlanTable.fetch(NursePlanFetcher.$.allTableFields()
                        .details(NursePlanDetailFetcher.$.allTableFields()
                                .item(NurseItemFetcher.$.allTableFields()))))
                .fetchOptional();
    }

    default Page<NursePlan> pageQuery(NursePlanPageInput inputVO){
        return sql().createQuery(nursePlanTable)
                .whereIf(StringUtils.hasText(inputVO.getPlanName()), () -> nursePlanTable.planName().like(inputVO.getPlanName()))
                .orderBy(nursePlanTable.id().desc())
                .select(nursePlanTable)
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

}